import os
from PIL import Image


def compress_image(image, quality=85):
    """压缩图片直到文件大小小于50KB"""
    import io

    while True:
        buffer = io.BytesIO()
        image.save(buffer, format="JPEG", quality=quality)
        size = buffer.tell()

        if size <= 50 * 1024 or quality < 10:  # 小于50KB或质量已经很低
            buffer.seek(0)
            return Image.open(buffer)

        # 调整质量
        quality = max(10, quality - 5)  # 最小质量设为10


def process_image(input_path, output_path):
    """处理单张图片：调整尺寸并压缩"""
    with Image.open(input_path) as img:
        # 调整尺寸为100x100
        img = img.resize((100, 100), Image.Resampling.LANCZOS)

        # 如果是RGBA模式，转换为RGB
        if img.mode == "RGBA":
            img = img.convert("RGB")

        # 压缩图片
        img = compress_image(img)

        # 保存图片
        img.save(output_path, "JPEG")
        print(f"已处理: {output_path}")


def main():
    """主函数：处理目录下所有PNG图片"""
    # 当前目录
    directory = os.getcwd()
    print(f"当前目录: {directory}")
    static_dir = directory + "\\static\\person"
    in_dir = static_dir + "\\in"
    out_dir = static_dir + "\\out"

    #     # 遍历目录下所有文件
    for filename in os.listdir(in_dir):
        if filename.lower().endswith(".png"):
            input_path = os.path.join(in_dir, filename)
            # 构建输出文件名，添加"out-"前缀并更改扩展名
            base_name = os.path.splitext(filename)[0]
            output_filename = f"out-{base_name}.jpg"
            output_path = os.path.join(out_dir, output_filename)

            print(f"正在处理: {input_path}")
            # 处理图片
            process_image(input_path, output_path)


if __name__ == "__main__":
    # 确保中文显示正常
    import matplotlib.pyplot as plt

    plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]

    main()
